<?php


abstract class TcpServcie
{
    protected $serv;
    public function __construct($conf)
    {
        $this->serv = new Swoole\Server($conf['host'], $conf['port']);
        $this->serv->set([
            'worker_num' => $conf['worker_num'],
            'max_request' => 4000,
            'task_worker_num' => $conf['task_worker_num'],
            'daemonize' => $conf['daemonize']
        ]);
        $this->serv->on('start', [$this, 'onStart']);
        $this->serv->on('workerStart', [$this, 'onWorkerStart']);
        $this->serv->on('connect', [$this, 'onConnect']);
        $this->serv->on('receive', [$this, 'onReceive']);
        $this->serv->on('task', [$this, 'onTask']);
        $this->serv->on('finish', [$this, 'onFinish']);
        $this->serv->on('close', [$this, 'onClose']);
    }
    public function onStart($serv){
        swoole_set_process_name("book_import_svr master process");
    }

    public function onManagerStart($serv)
    {
        swoole_set_process_name("book_import_svr manager process");
    }

    public function onWorkerStart($server, $worker_id)
    {
        register_shutdown_function(function () {
            $error = error_get_last();
            if (!empty($error)) {
                \svrlog\LogComponent::writeLog()->error($error['message'] . ' file: ' . $error['file']);
            }
        });
        if ($worker_id >= $server->setting['worker_num']) {
            swoole_set_process_name("book_import_svr task process");
        } else {
            swoole_set_process_name("book_import_svr worker process");
        }
    }

    public function onConnect($serv, $fd)
    {

    }

    public function onClose($serv, $fd)
    {
        var_dump($fd);
    }

    abstract public function onReceive($serv, $fd, $from_id, $data);

    abstract public function onTask($serv, $task_id, $from_id, $data);

    abstract public function onFinish($serv, $task_id, $data);

    public function start()
    {
        $this->serv->start();
    }
}